﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;

namespace SqlDao
{
    internal class Log
    {
        private static void Record( String msg) {
            string currentDate = DateTime.Now.ToString("yyyy-MM-dd ");
            msg = DateTime.Now.ToString(" hh:mm:ss") + "---------> \t" + msg + "\r\n";
            string dir = AppDomain.CurrentDomain.BaseDirectory.ToString();
            string path = Path.Combine(dir, "sqlDao");

            if (!Directory.Exists(path))
            {
                new DirectoryInfo(path).Create();
            }
            string fileName = path + "\\" + "log_" + currentDate + ".txt";

            if (!File.Exists(fileName))
            {
                File.Create(fileName);
            }

            WriteAppend(fileName, msg);
        }

        /// <summary>
        /// 将日志信息保存到 运行时根目录下的/log/log当天日期.txt
        /// </summary>
        /// <param name="msg"></param>
        public static void Info(string msg)
        {
            if (String.IsNullOrEmpty(msg))
            {
                return;
            }
            try {
                Record(msg);
            }catch(Exception ex) {
                if (DbHelper.isDebug) {
                    Console.WriteLine("--->sql dao :" + ex.Message);
                    Debug.WriteLine("--->sql dao :" + ex.Message);
                }
            }
        }
    
        /// <summary>
        /// 写文件
        /// </summary>
        /// <param name="path">路径</param>
        /// <param name="content">内容</param>
        private static void WriteAppend(string path, string content)
        {
            using (FileStream fs = new FileStream(path, FileMode.Append, FileAccess.Write))
            {
                fs.Position = fs.Length;
                using (StreamWriter writer = new StreamWriter(fs))
                {
                    writer.BaseStream.Seek(0, SeekOrigin.End);
                    writer.Write(content);
                    writer.Flush();
                }
            }
        }
    }
}
